﻿(function () {
    SureOrderClass = {};
    var _currentOrder = null;
    var _totalAmount = 0;
    var islock = false;//防止同时提交两次数据
    var _shipAmount = 0;
    var _couponAmount = 0;
    var _productAmount = 0;
    var _couponId = 0;
    var paydata = {};
    var _spid = ToolManager.Common.UrlParms("spid");
    var _said = ToolManager.Common.UrlParms("said"); 
    var _iscart = ToolManager.Common.UrlParms("iscart");//是否是来自购物车结算
    var _coupons = [];
    var _addressList = [];
    var _isCanCreateOrder = true;//获取运费失败，给false
    var _defaultAddress = null;//使用的地址，下单进来默认取默认的
    var _addressid = ToolManager.Common.UrlParms("addresid");//设置地址时，点击带回来的，
    var _orderNo = "";
    SureOrderClass.Instance = {
        Init: function () {
            $(function () {
                _currentOrder = JSON.parse($("#hidden_pModel").val());
                _productAmount = parseFloat($("#product_amount").text());
                _totalAmount = parseFloat($("#total_amount").text()).toFixed(2);
                SureOrderClass.Instance.GetUserCoupons();
                SureOrderClass.Instance.GetConsigneeList();
            });
            $(document).on('click', '#btn_createOrder', this.CreateOrder);
            $(document).on('change', '#coupon_select', this.ChangeCoupon);
        },

        GetConsigneeList: function () {
            var index = layer.load(1);
            $.get("/ConSignee/GetList?spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    if (data.Data.length) {
                        _addressList = data.Data;
                        if (_addressid != '0') {
                            //列表设置回来的
                            _defaultAddress = SureOrderClass.Instance.GetAddressModel(_addressid);

                        } else {
                            //下单，，取默认的
                            for (var i = 0; i < data.Data.length; i++) {
                                if (data.Data[i].IsDefault == 1) {
                                    _defaultAddress = data.Data[i];
                                    break;
                                }
                            }
                        }
                        var htmlArr = [];
                        if (_defaultAddress == null) {
                            htmlArr.push('<span>点击设置地址</span>');
                        } else {
                            htmlArr.push('<h4 class="address-name"><span>' + _defaultAddress.ConsigneeName + '</span><span>' + _defaultAddress.ConsigneePhone + '</span></h4>');
                            htmlArr.push('<div class="address-txt">' + (_defaultAddress.ProvinceName + _defaultAddress.CityName + _defaultAddress.AreaName + _defaultAddress.Address) + '</div>');
                        }
                        $("#address_msg").html(htmlArr.join(''));
                        SureOrderClass.Instance.GetShipAmount();
                    } else {
                        $("#address_msg").html('<span>点击设置地址</span>');
                    }
                } else {
                    layer.msg(data.Message);
                }
            });
        },

        GetShipAmount: function () {
            if (_defaultAddress == null)
                return false;
            _shipAmount = 0;
            _totalAmount = SureOrderClass.Instance.GetTotalAmount();
            $("#total_amount").text(_totalAmount);

            var products = [];
            for (var i = 0; i < _currentOrder.length; i++) {
                products.push({
                    ProvinceCode: _defaultAddress.ProvinceCode,
                    ProductName: _currentOrder[i].SkuDetail.ProductName,
                    ProductId: _currentOrder[i].ProductId,
                    SaleNum: _currentOrder[i].SaleNum,
                    Product_SkuId: _currentOrder[i].Product_SkuId,
                    Weight: _currentOrder[i].SkuDetail.Weight,
                    ShippingTemplateId: _currentOrder[i].SkuDetail.ShippingTemplateId
                });
            }
            var index = layer.load(1);
            RequestManager.Ajax.Post("/Order/CountShipAmount?spid="+_spid, {
                Spid: _spid,
                TotalProductAmount: _productAmount,
                ProvinceCode: _defaultAddress.ProvinceCode,
                Products: products
            }, true, function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    _shipAmount = data.Data;
                    _totalAmount = SureOrderClass.Instance.GetTotalAmount();
                    $("#total_amount").text(_totalAmount);
                    $("#ship_amount").text(_shipAmount);
                } else {
                    layer.msg(data.Message);
                    _isCanCreateOrder = false;
                }
            })
        },
        ChangeCoupon: function () {
           
            //每次改变，初始化各个金额，防止选择金额后，又不选，优惠金额还在
            _totalAmount = (_productAmount + _shipAmount).toFixed(2);
            _couponAmount = 0;
            $("#total_amount").text(_totalAmount);
            $("#coupon_amount").text(_couponAmount);

            if ($(this).val() == "0")
                return false;
            var coupon = SureOrderClass.Instance.GetCouponModel($(this).val());
            if (coupon.CouponType == 1) {
                //满减券
                if (_productAmount < coupon.MinOrderAmount) {
                    layer.msg("未达到满减金额");
                    $("#coupon_select").val("0");
                    return false;
                } else {
                    _couponId = $(this).val();
                    _couponAmount = coupon.DelAmount;
                    $("#coupon_amount").text(_couponAmount);
                    _totalAmount = SureOrderClass.Instance.GetTotalAmount();
                    $("#total_amount").text(_totalAmount);
                }
            } else if (coupon.CouponType == 2) {
                //折扣券
                _couponAmount = (((100 - coupon.Discount) / 100) * _productAmount).toFixed(2);
                //测试如果是1分钱得话
                if (_couponAmount < 0.01)
                    _couponAmount = 0.01;
                _couponId = $(this).val();
                $("#coupon_amount").text(_couponAmount);
                _totalAmount = SureOrderClass.Instance.GetTotalAmount();
                $("#total_amount").text(_totalAmount);
            }
        },
        GetUserCoupons: function () {
            var index = layer.load(1);
            $.get("/Marketing/GetUserCoupon?spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    var html = [];
                    if (data.Data.length > 0) {
                        _coupons = data.Data;
                        html.push('<select class="fr" id="coupon_select" >');
                        html.push(' <option value="0">请选择</option>');
                        for (var i = 0; i < data.Data.length; i++) {
                            html.push('<option value="' + data.Data[i].CouponId + '">' + data.Data[i].CouponName + '</option>');
                        }
                        html.push('</select>');

                    } else {
                        html.push('<span class="fr txt-color-red">暂无</span>');
                    }
                    $("#coupon_div").html(html.join(''));
                } else {
                    _isCanCreateOrder = false;
                    layer.msg(data.Message);
                }
            });
        },
        GetCouponModel: function (couponId) {
            var res = null;
            for (var i = 0; i < _coupons.length; i++) {
                if (couponId == _coupons[i].CouponId) {
                    res = _coupons[i];
                    break;
                }
            }
            return res;
        },
        GetAddressModel: function (addressid) {
            var res = null;
            for (var i = 0; i < _addressList.length; i++) {
                if (addressid == _addressList[i].Id) {
                    res = _addressList[i];
                    break;
                }
            }
            return res;
        },
        GetTotalAmount: function () {
            return (_productAmount + _shipAmount - _couponAmount).toFixed(2);
        },
        CreateOrder: function () {
            if (islock)
                return false;
            islock = true;
            if (!_isCanCreateOrder) {
                layer.msg("存在异常,请联系客服");
                islock = false;
                return false;
            }
            if (_defaultAddress == null) {
                layer.msg("请选择地址");
                islock = false;
                return false;
            }
            var couponId = $("#coupon_select").val();
            var products = [];
            for (var i = 0; i < _currentOrder.length; i++) {
                products.push({
                    ProductId: _currentOrder[i].ProductId,
                    SaleNum: _currentOrder[i].SaleNum,
                    Product_SkuId: _currentOrder[i].Product_SkuId,
                });
            }
            var model = {};
            model.Spid = _spid;
            model.Said = _said;
            model.ConsigneeId = _defaultAddress.Id;
            model.ShipAmount = _shipAmount;
            model.CouponId = _couponId;
            model.Remarks = $("#txt_remark").val();
            model.ToalAmount = _totalAmount;
            model.AppType = 2;
            model.Api_CreateOrder_ProductItems = products;
            
            var index = layer.load(1);
            RequestManager.Ajax.Post("/Order/Create?spid="+_spid, model, true, function (data) {
                layer.close(index);
                islock = false;
                if (data.IsSuccess) {
                    //删除购物车商品
                    if (_iscart == '1')
                        SureOrderClass.Instance.DeleteCart();
                    //获取证书并构建
                    paydata["appId"] = data.Data.PayParamater.AppId;
                    paydata["timeStamp"] = data.Data.PayParamater.TimeStamp;
                    paydata["nonceStr"] = data.Data.PayParamater.NonceStr;
                    paydata["package"] = data.Data.PayParamater.Package;
                    paydata["signType"] = data.Data.PayParamater.SignType;
                    paydata["paySign"] = data.Data.PayParamater.PaySign;
                    _orderNo = data.Data.PayParamater.Orderno;
                    SureOrderClass.Instance.ToPay();

                } else {
                    layer.msg(data.Message);
                    layer.alert("拉起支付失败请重新下单!", function () {
                        window.location.href = "/Order/MyOrders?orderStatus=999&spid=" + _spid + "&said=" + _said + "&canback=0";
                    });
                }
            })
        },
        DeleteCart:function(){
            $.get("/Cart/GetList?said=" + _said + "&spid=" + _spid + "&r=" + new Date().getTime(), function (data) {
                if (data.IsSuccess) {
                    if (data.Data.length > 0) {
                        //删除
                        var skuIdArr = [];
                        for (var i = 0; i < _currentOrder.length; i++) {
                            skuIdArr.push(_currentOrder[i].Product_SkuId);
                        }
                        var list = ShopCartManagerClass.Instance.DeleteSkuBySkuIdArr(data.Data, skuIdArr);
                        //更新回购物车缓存
                        RequestManager.Ajax.Post("/Cart/Set?spid=" + _spid + "&said=" + _said, list, true, function (data) {
                           
                        })
                    } 

                } else {
                    //layer.msg(data.Message);
                }
            })
        },
        ToPay: function () {
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', SureOrderClass.Instance.onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', SureOrderClass.Instance.onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', SureOrderClass.Instance.onBridgeReady);
                }
            } else {
                SureOrderClass.Instance.onBridgeReady();
            }
        },
        onBridgeReady: function () {
            WeixinJSBridge.invoke(
            'getBrandWCPayRequest', paydata,
            function (res) {
                if (res.err_msg.indexOf('ok') > -1) {
                    SureOrderClass.Instance.GoResult();
                } else if (res.err_msg.indexOf('cancel') > -1) {
                    alert("用户取消了支付。");
                    window.location.href = "/Order/MyOrders?orderStatus=999&spid=" + _spid + "&said=" + _said+"&canback=0";
                } else {
                    alert("支付出现错误，支付失败。");
                    try {
                        $.get("/Error/Write?error=" + JSON.stringify(res) + "&r=" + new Date().getTime(), function (data) {
                            if (data.IsSuccess) {
                               
                            } else {
                                layer.alert(data.Message);
                            }
                        })
                    } catch (e) { }
                    window.location.href = "/Order/MyOrders?orderStatus=999&spid=" + _spid + "&said=" + _said + "&canback=0";
                    //alert(res.err_msg);//使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                }
            }
            )
        },
        GoResult: function () {
            var index = layer.load(1);
            $.get("/Order/GetPayResult?orderno=" + _orderNo + "&spid="+_spid+"&r=" + new Date().getTime(), function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    var result = data.Data;
                    if (result.code == "SUCCESS") {
                        switch (result.state) {
                            case "SUCCESS":
                                //window.location.href = "./orderinfo.aspx?spid=" + $("#hid_spid").val() + "&orderno=" + orderno;
                                //跳转支付成功页面
                                window.location.href = "/Order/MyOrders?orderStatus=999&spid=" + _spid + "&said=" + _said + "&canback=0";
                                break;
                            case "USERPAYING":
                                $("#btn_createOrder").text("支付处理中");
                                setTimeout(SureOrderClass.Instance.GoResult, 4000);
                                break;
                            case "REFUND":
                            case "NOTPAY":
                            case "CLOSED":
                            case "PAYERROR":
                            case "REVOKED":
                                $("#btn_createOrder").text("支付处理中");
                                break;
                        }
                       
                    }
                    else {
                        layer.alert(result.msg, { icon: 0 });
                       
                    }
                }
                else {
                    layer.alert(data.Message, { icon: 0 });
                    
                }
            })


           
        }
    }
})()